package com.aaa.forum.controller;


import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.exception.ApplicationException;
import com.aaa.forum.model.Board;
import com.aaa.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "板块接口")
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    // :9 表示, 如果没有找到该配置项, 那么就使用9作为它的值
    @Value("${forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;

    /**
     * 获取首页板块列表
     * @return  板块集合
     */
    @ApiOperation("获取首页板块列表")
    @GetMapping("/navList")
    public AppResult<List<Board>> navList() {
        log.info("IndexBoardNum = " + indexBoardNum);
        List<Board> boards = boardService.selectByNum(indexBoardNum);

        // 如果为空, 让它返回一个空的集合, 不返回 null
        if (boards == null) boards = new ArrayList<>();

        return AppResult.success(boards);
    }

    /**
     * 根据id获取板块信息
     * @param id    板块id
     * @return      板块信息
     */
    @ApiOperation("根据id获取板块信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@ApiParam("板块id") @RequestParam("id") Long id) {
        // 调用Service获取板块信息
        Board board = boardService.selectById(id);
        // 板块状态校验
        if (board == null || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 如果查询不到板块, 或者该板块已被删除
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 返回结果
        return AppResult.success(board);
    }
}
